<style lang="less">
	.draw {
		position: relative;
		height: 100%;
		background: rgba(0, 0, 0, 0.85);
		.draw-handle-bar {
			height: 120rpx;
			background: #fff;
			.handle-btn {
				color: rgba(0, 0, 0, 0.85);
				.handle-btn__icon {
					font-size: 44rpx;
				}
				.handle-btn__text {
					margin-top: 8rpx;
					font-size: 24rpx;
					line-height: 34rpx;
				}
			}
			.handle-btn--next {
				color: var(--theme);
				.handle-btn__icon {
					transform: rotate(180deg);
				}
			}
		}
	}
</style>

<template>
	<view class="draw flex flex-col">
		<!-- 返回按钮 -->
		<back-btn @click="backHome" />
		<!-- 预览区 -->
		<view class="preview flex-1 flex just-center align-center">
			<image class="preview-image" :src="originUrl" :mode="mode" :style="{ width: previewImageStyle.width, height: previewImageStyle.height }" />
		</view>
		<!-- 底部操作栏 -->
		<view class="draw-handle-bar flex align-center" :class="isIphoneX ? 'iphoneX-bottom' : ''">
			<view class="handle-btn flex-1 flex flex-col just-center align-center" @click="addWatermark">
				<view class="handle-btn__icon iconfont icon-sticker flex flex-col just-center"></view>
				<view class="handle-btn__text">水印</view>
			</view>
			<view class="handle-btn flex-1 flex flex-col just-center align-center">
				<view class="handle-btn__icon iconfont icon-border flex flex-col just-center" @click="addFrame"></view>
				<view class="handle-btn__text">相框</view>
			</view>
			<view class="handle-btn flex-1 flex flex-col just-center align-center handle-btn--next" @click="saveImageToPhotosAlbum">
				<view class="handle-btn__icon iconfont icon-left flex flex-col just-center"></view>
				<view class="handle-btn__text">下一步</view>
			</view>
		</view>
		<!-- 加相框 -->
		<frame v-if="frameShow" @close="closeFrame" @submit="closeFrame" />
		<!-- 加水印 -->
		<watermark v-if="watermarkShow" @close="closeWatermark" @submit="closeWatermark" />
	</view>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import systemMixin from '@/mixin/system'
import { funcSync } from '@/utils/index'
import Frame from '@/biz-components/frame'
import Watermark from '@/biz-components/watermark'
import BackBtn from '@/biz-components/back-btn'
const { mapState, mapMutations } = createNamespacedHelpers('app')
/**
 * 编辑页
 */
export default {
	name: 'Edit',
	mixins: [systemMixin],
	components: {
		Frame,
		Watermark,
		BackBtn,
	},
	data() {
		return {
			frameShow: false, // 显示加相框
			watermarkShow: false, // 显示加水印
		}
	},
	computed: {
		...mapState(['originUrl', 'localUrl', 'mode']),
		    // 预览图样式
		previewImageStyle(state) {
			if (this.mode === 'widthFix') {
				return { width: '100%', height: 'auto' }
			}
			return { width: 'auto', height: '100%' }
		},
	},
	methods: {
		...mapMutations(['setMode']),
		// 获取预览区
		getPreview() {
			return new Promise((resolve, reject) => {
				try {
					uni.createSelectorQuery()
						.select('.preview')
						.fields({ size: true })
						.exec(res => {
							resolve(res[0])
						})
				} catch(err) {
					reject(err)
				}
			})
		},
		// 获取图片模式
		async getImageMode() {
			// 获取预览区宽高
			const { width: preWidth, height: preHeight } = await this.getPreview()
			// 获取图片宽高
			const { errMsg, width: imgWidth, height: imgHeight } = await funcSync(uni.getImageInfo, { src: this.originUrl })
			// 未获取到图片信息
			if (!imgWidth) {
				console.error(errMsg)
				return
			}
			const preRatio = preWidth / preHeight	// 预览区宽高比
			const imgRatio = imgWidth / imgHeight // 图片宽高比
			if (preRatio > imgRatio) {
				this.setMode('heightFix')
				return
			}
			this.setMode('widthFix')
		},
		// 获取预览图片
		getPreviewImage() {
			return new Promise((resolve, reject) => {
				try {
					uni.createSelectorQuery()
						.select('.preview-image')
						.fields({ size: true })
						.exec(res => {
							resolve(res[0])
						})
				} catch(err) {
					reject(err)
				}
			})
		},
		// 保存到相册
		async saveImageToPhotosAlbum() {
			uni.showLoading({	title: '保存中' })	// 加载动画
			const { errMsg } = await funcSync(uni.saveImageToPhotosAlbum, { filePath: this.localUrl }, uni.hideLoading)
			uni.hideLoading()	// 关闭加载动画
			// 取消保存
			if (errMsg === 'saveImageToPhotosAlbum:fail cancel') {
				console.error(errMsg)
				return
			}
			// 保存成功, 返回首页
			if (errMsg === 'saveImageToPhotosAlbum:ok') {
				uni.redirectTo({ url: '/pages/share' })
				return
			}
			// 拒绝授权
			if (errMsg === 'saveImageToPhotosAlbum:fail auth deny' || errMsg === 'saveImageToPhotosAlbum:fail:auth denied' || errMsg === 'saveImageToPhotosAlbum:fail authorize no response') {
				const { confirm } = await funcSync(uni.showModal, { content: '您未授权, 是否跳转设置?', cancelText: '取消', cancelColor: '#999999', confirmText: '确认', confirmColor: '#FF597A' })
				if (confirm) {
					uni.openSetting({
					fail: (err) => {
						console.error(err)
					}
				})
					return
				}
				uni.showToast({ icon: 'none',	title: '保存失败!请授权保存相册权限!' })
				return
			}
			// 保存失败
			uni.showToast({ icon: 'none',	title: '保存失败!' })
			throw errMsg
		},
		// 返回首页
		async backHome() {
			const { confirm } = await funcSync(uni.showModal, { content: '是否放弃当前所操作的图片?', cancelText: '不放弃', cancelColor: '#999999', confirmText: '放弃', confirmColor: '#FF597A' })
			// 确认返回
			if (confirm) {
				uni.navigateBack({ delta: 1 })
			}
		},
		// 加相框
		addFrame() {
			this.frameShow = true
		},
		async closeFrame() {
			this.frameShow = false
			await this.getImageMode()
		},
		addWatermark() {
			this.watermarkShow = true
		},
		async closeWatermark() {
			this.watermarkShow = false
			await this.getImageMode()
		},
	},
	async onShow() {
		await this.getImageMode()
	}
}
</script>